package com.cd.javacxy.module.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cd.javacxy.common.model.entity.CxyUser;
import com.cd.javacxy.common.model.query.UserQuery;
import com.cd.javacxy.common.model.vo.CxyUserVo;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.common.utils.CxyUtils;
import com.cd.javacxy.exception.BaseException;
import com.cd.javacxy.exception.UserNotFoundException;
import com.cd.javacxy.module.web.dao.CxyUserDao;
import com.cd.javacxy.module.web.service.CxyUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * CxyUser的服务接口的实现类
 *
 * @author yanghy
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CxyUserServiceImpl implements CxyUserService {

    private final CxyUserDao cxyUserDao;


    @Override
    public CxyUserVo login(String account, String password) {
        UserQuery query = new UserQuery();
        query.setEmail(account);
        CxyUser cxyUser = cxyUserDao.findUserByEmail(query);
        if (cxyUser == null) {
            throw new UserNotFoundException("用户不存在");
        }
        if (!CxyUtils.encode(password).equals(cxyUser.getPassword())) {
            throw new UserNotFoundException("密码错误");
        }
        CxyUser updateUser = new CxyUser();
        CxyUserVo userVo = new CxyUserVo();
        updateUser.setUserId(cxyUser.getUserId());
        updateUser.setLastLoginTime(LocalDateTime.now());
        this.cxyUserDao.updateNotNullCxyUserById(updateUser);
        BeanUtil.copyProperties(cxyUser, userVo);


        return userVo;
    }

    /*@Override
    public CxyUserVo login(String username, String password) {
        //用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername()去验证用户名和密码，
            // 如果正确，则存储该用户名密码到security 的 context中
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new BaseException("用户名或密码错误", 402);
            } else if (e instanceof DisabledException) {
                throw new BaseException("账户被禁用", 402);
            } else if (e instanceof AccountExpiredException) {
                throw new BaseException("账户过期无法验证", 402);
            } else {
                throw new BaseException("账户被锁定,无法登录", 402);
            }
        }
        //存储认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        SessionUser userDetail = (SessionUser) authentication.getPrincipal();
        return null;
    }*/

    @Override
    public CxyUserVo findUserByEmail(String email) {
        UserQuery query = new UserQuery();
        query.setEmail(email);
        CxyUser cxyUser = cxyUserDao.findUserByEmail(query);
        CxyUserVo userVo = new CxyUserVo();
        BeanUtil.copyProperties(cxyUser, userVo);
        return userVo;
    }

    @Override
    public CxyUserVo findUserByUserId(Integer userId) {
        UserQuery query = new UserQuery();
        query.setUserId(userId);
        CxyUser cxyUser = cxyUserDao.findUserByUserId(query);
        CxyUserVo userVo = new CxyUserVo();
        BeanUtil.copyProperties(cxyUser, userVo);
        return userVo;
    }

    @Override
    public CxyUserVo findUserInfo4UserHome(Integer userId) {
        CxyUserVo user = this.findUserByUserId(userId);
        if (user == null) {
            return null;
        }
        user.setPassword(null);
        user.setActivationCode(null);
        return user;
    }

    @Override
    public CxyUserVo findUserInfofUserHome(Integer userId) {
        return null;
    }
    /*public CxyUserVo findUserByUserName(String userName) {
		UserQuery userQuery = new UserQuery();
		userQuery.setUserName(userName);
		List<CxyUser> userList = userMapper.selectList(userQuery);

		return null;
	}

	public CxyUserVo findUserByEmail(String email) {
		UserQuery userQuery = new UserQuery();
		userQuery.setEmail(email);
		List<CxyUser> userList = userMapper.selectList(userQuery);

		return null;
	}
	public CxyUserVo findUserByUserid(Integer userid) {
		UserQuery userQuery = new UserQuery();
		userQuery.setUserId(userid);
		List<CxyUser> userList = userMapper.selectList(userQuery);

		return null;
	}*/

    @Override
    public String findHeadIcon(String account) {
        try {
            CxyUserVo user = null;
            if (account.contains(Constants.AT)) {
                user = this.findUserByEmail(account);
            }
            if (user == null) {
                throw new BaseException("用户不存在");
            }
            return user.getUserIcon();
        } catch (Exception e) {
            log.error("获取用户头像失败，account={}", account, e);
        }
        return "";
    }

    @Override
    public int addMark(Integer mark, Integer userId) {
        return changeMark(userId, mark);
    }

    @Override
    public int changeMark(Integer userId, int mark) {
        return this.cxyUserDao.changeUserMark(mark, userId);
    }
}